package hong.jun.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import javax.sql.DataSource;
import java.util.Arrays;

//OAUTH2 认证服务配置
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    //设置JWT签名密钥。它可以是简单的MAC密钥，也可以是RSA密钥
    private final String sign_key  = "123";

    //第一步 ，客户端详情配置 ================================================================

    //密码匹配器：用来给秘钥加密
    @Autowired
    private PasswordEncoder passwordEncoder;
    //注入数据源
    @Autowired
    private DataSource dataSource ;

    //基于内存的客户端详情配置
  /*  @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //基于内存的客户端详情配置 ：创建一个  InMemoryClientDetailsService 类
        clients.inMemory()
                //参数：&client_id=webapp
                .withClient("hongjun")
                //参数：秘钥 &secret=xxxz
                .secret(passwordEncoder.encode(sign_key))
                //资源id
                .resourceIds("res1")
                //支持的授权模式
                .authorizedGrantTypes("client_credentials","password","authorization_code","refresh_token")
                //授权范围
                .scopes("all")
                //自动授权
                .autoApprove(false)
                //授权码回调地址
                .redirectUris("http://www.baidu.com");
    }*/
    //定义针对于数据库的客户端配置详情服务
    @Bean
    public ClientDetailsService clientDetailsService(){
        JdbcClientDetailsService jdbcClientDetailsService = new JdbcClientDetailsService(dataSource);
        //设置密码编码
        jdbcClientDetailsService.setPasswordEncoder(passwordEncoder);
        return jdbcClientDetailsService;
    }
    //修改ClientDetailsServiceConfigurer 使用基于jdbc的客户端详情配置方案
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //配置成基于jdbc的客户端详情方案
        clients.withClientDetails(clientDetailsService());
    }
    //第二步 ，授权服务端点配置(授权码和令牌管理)================================================

   /* //token的存储方案
    @Bean
    public TokenStore tokenStore(){
        return new InMemoryTokenStore();
    }*/

    /**JWT*/
    @Bean
    public TokenStore tokenStore(){
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    //JWT令牌校验工具
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter jwtAccessTokenConverter =
                new JwtAccessTokenConverter();
        //设置JWT签名密钥。它可以是简单的MAC密钥，也可以是RSA密钥
        jwtAccessTokenConverter.setSigningKey(sign_key);
        return jwtAccessTokenConverter;
    }

    //注入客户端详情配置的service
    @Autowired
    private ClientDetailsService clientDetailsService;

    //配置令牌服务
    /*@Bean
    public AuthorizationServerTokenServices tokenService(){
        //创建默认的令牌服务
        DefaultTokenServices services = new DefaultTokenServices();
        //指定客户端详情配置
        services.setClientDetailsService(clientDetailsService);
        //支持产生刷新token
        services.setSupportRefreshToken(true);
        //token存储方式
        services.setTokenStore(tokenStore());
        //token有效时间2小时
        services.setAccessTokenValiditySeconds(72000);
        //刷新令牌默认有效时间
        services.setRefreshTokenValiditySeconds(200000);
        return services;
    }
*/
    /**配置令牌服务*/
    @Bean
    public AuthorizationServerTokenServices tokenService(){

        //创建默认的令牌服务
        DefaultTokenServices services = new DefaultTokenServices();
        //设置客户端信息服务
        services.setClientDetailsService(clientDetailsService);
        //支持token刷新
        services.setSupportRefreshToken(true);
        //token存储方式
        services.setTokenStore(tokenStore());

        //设置token增强 - 设置token转换器
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter()));
        services.setTokenEnhancer(tokenEnhancerChain);  //jwtAccessTokenConverter()

        //token有效时间2小时
        services.setAccessTokenValiditySeconds(72000);
        //属性令牌默认有效时间
        services.setRefreshTokenValiditySeconds(200000);
        return services;
    }


    //基于内存的授权码服务
  /*  @Bean
    public AuthorizationCodeServices authorizationCodeServices(){
        return new InMemoryAuthorizationCodeServices();
    }*/
  /*基于数据库的授权服务*/
    @Bean
    public AuthorizationCodeServices authorizationCodeServices(){
        //return new InMemoryAuthorizationCodeServices();
        return new JdbcAuthorizationCodeServices(dataSource);
    }


    //认证管理器，密码模式用到
    @Autowired
    private AuthenticationManager authenticationManager;


    /**授权服务端点配置(授权码和令牌管理)*/
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        //配置认证管理器
        endpoints.authenticationManager(authenticationManager)
                //令牌服务配置
                .tokenServices(tokenService())
                //授权码服务配置
                .authorizationCodeServices(authorizationCodeServices())
                //允许用post
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }

    /**第三部，授权服务安全配置*/
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                //对应/oauth/token_key 公开
                .tokenKeyAccess("permitAll()")
                //对应/oauth/check_token ，路径公开
                .checkTokenAccess("permitAll()")
                //允许客户端进行表单身份验证,使用表单认证申请令牌
                .allowFormAuthenticationForClients();
    }
}
